clear


set graphics off
set seed [withheld]


*Iterations
local RR=${masteriter}

local n_prod_vars=1

/*This first section constructs the permutations. */

local samplelist $samplelist
foreach sample in `samplelist'{

	if("`sample'"=="young${routine}" | "`sample'"=="youngold${routine}" | "`sample'"=="old${routine}"){
		local agegroup "youngold${routine}"
		}
	else{
		local agegroup "`sample'"
		}
	
	
		
	quietly use "${data}/data_`agegroup'.dta", clear

		
	if("`sample'"=="young${routine}"){
		keep if age<=5
		}
	if("`sample'"=="old${routine}"){
		keep if age>5
		}	

local full_sample_obs = r(N)
quietly ren (tfpvar  ) (lprod_1  )
local use_sample_obs = r(N)

tempfile AA BB
quietly save `AA'

*Conditional Order of Plants --> gives vector of locations
bys  T J (order) : gen cond_order = _n
quietly keep  S T J cond_order
quietly save `BB'

forvalues rr=0(1)`RR' {

*Zero Iteration is True Values
if `rr'==0 {
	* Loop Through The TFP Variables
	forvalues nn=1(1)`n_prod_vars' {
		tempfile C`nn' D`nn'
	}
	forvalues nn=1(1)`n_prod_vars' {
		use `AA', clear
		run "${code}/Permute_worker.do" `nn'
		quietly save `D`nn''
		*gen kdensity
		
		if("`sample'"=="all") {
			foreach var in capT tau {

			    tempvar weight
			     gen `weight'=1
			     if "`var'"=="tau"{
				  replace `weight'=empshare_SJT
				  }

				quietly sum `var', d
				quietly gen p95_`var'	=r(p95)
				quietly gen p5_`var'	=r(p5)
				kdensity `var' [aw=`weight'], n(50) generate(`var'_x `var'_d)
			}
		quietly keep capT_x capT_d tau_x tau_d p95_* p5_*
		quietly keep if capT_x!	=.
		quietly gen iter		=`rr'
		quietly save "${results}/temp/permute_kdenspoints_`sample'_prodvar`nn'_${date}.dta", replace
		}
		
		quietly use `D`nn'', replace
		quietly keep if _n==1 
		quietly keep  var* 
		quietly save `C`nn''
	}

	use `C1',clear
	quietly cap drop _m
	quietly gen iter	= `rr'
	quietly save "${results}/temp/permute_out_stats_`sample'_${date}.dta", replace

} 
else {
/*
Positive Iterations Use Randomized Location
*/
	use `AA', clear
	quietly gen randu = runiform()
	quietly bys  T J (randu) : gen cond_order = _n
	quietly ren S true_location
	quietly merge 1:1  T J cond_order using `BB'
	tempfile AB
	quietly save `AB'

	forvalues nn=1(1)`n_prod_vars' {
		tempfile C`nn' D`nn'
		}
	forvalues nn=1(1)`n_prod_vars' {
		use `AB', clear
		run "${code}/Permute_worker.do" `nn'
		quietly save `D`nn''
		*Gen kdensity plot here
		if("`sample'"=="all"){
			foreach var in capT tau {
			    tempvar weight
			     gen `weight'=1
			     if "`var'"=="tau"{
				  replace `weight'=empshare_SJT
				  }
				quietly sum `var', d
				quietly gen p95_`var'	=r(p95)
				quietly gen p5_`var'	=r(p5)
				kdensity `var' [aw=`weight'], n(50) generate(`var'_x `var'_d)
			}
			quietly keep capT_x capT_d tau_x tau_d p95_* p5_*
			quietly keep if capT_x!=.
			quietly gen iter=`rr'
			quietly append using "${results}/temp/permute_kdenspoints_`sample'_prodvar`nn'_${date}.dta"
			quietly save "${results}/temp/permute_kdenspoints_`sample'_prodvar`nn'_${date}.dta", replace
		}
		
		quietly use `D`nn'', replace
		quietly keep if _n==1 
		quietly keep var*
		quietly save `C`nn''
	}

	* Merge the files
	use `C1',clear
	quietly cap drop _m
	forvalues nn=2(1)`n_prod_vars' {
		quietly merge 1:1 _n using `C`nn'', nogen
	}
	
	quietly gen iter	= `rr'
	
	quietly  append using "${results}/temp/permute_out_stats_`sample'_${date}.dta"
	quietly  save "${results}/temp/permute_out_stats_`sample'_${date}.dta", replace
}

}
di "`sample'"
}

local n_prod_vars=1

foreach sample in `samplelist'{
forvalues ii=1/`n_prod_vars' {
foreach svar in capT tau {
	local var var
	use "${results}/temp/permute_out_stats_`sample'_${date}.dta", clear
	*Get true value as local
	sort iter
	local trueval_`var'			=`var'_`svar'_`ii'[1]
	local truevalprint_`var' 	= string(`trueval_`var'', "%05.3f")
	*Get mean value as local
	 qui sum `var'_`svar'_`ii' if iter!=0, d
	local meanval_`var'			=r(mean)
	local sdval_`var'			=r(sd)
	local meanvaltable_`var' 	= string(`meanval_`var'', "%09.4g")
	local sdvaltable_`var' 	= string(`sdval_`var'', "%09.4g")
	*Get pval as local
	sort `var'_`svar'_`ii'
	tempvar pval_`var'
	gen `pval_`var''			=_n
	sort iter
	local tablepval_`var'		=(_N-`pval_`var''[1])/`RR'
	local pval_`var'			=`pval_`var''[1]
	if("`svar'"=="capT"){
	local xtitle "Variance of Location Effects"
	}
	if("`svar'"=="tau"){
	local xtitle "Variance of Industry-Specific Location Effectss"
	}



clear
set obs 1

quietly gen perm_`var'_`svar'_mean=`meanvaltable_`var''
quietly gen perm_`var'_`svar'_pval=`tablepval_`var''
quietly gen perm_`var'_`svar'_sd=`sdvaltable_`var''


quietly gen sample="`sample'"
merge 1:1 sample using "${results}/temp/results${date}${routine}.dta", nogen
save "${results}/temp/results${date}${routine}.dta", replace

*Pick permutation closest to mean for figure 1 permutate kdensity plot
if("`sample'"=="all"){
	use "${results}/temp/permute_out_stats_`sample'_${date}.dta" if iter!=0, clear
	gen absdif=abs(`meanvaltable_`var''-`var'_`svar'_`ii')
	sort absdif
	local optimaliter=iter[1]
	use "${results}/temp/permute_kdenspoints_`sample'_prodvar`ii'_${date}.dta" if iter==`optimaliter', replace
	save "${results}/temp/permute_kdenspoints_`sample'_prodvar`ii'_optimal_`svar'_`var'_${date}.dta", replace
	}

}
}
}
